﻿using System;
using System.Collections.Generic;
using BigfootDNN.Mvc;
using YourCompany.Modules.MvcTemplate.Model;

namespace YourCompany.Modules.MvcTemplate.ViewModel
{
   
    public class TimesheetViewModel
    {
        public List<TimesheetItem> Items;

        public static TimesheetViewModel Create(RouteInfo route)
        {
            // Create a new View Model
            var vm = new TimesheetViewModel();
            // Retreive the timesheet items for this user for the last fours weeks
            vm.Items = route.App.DB.SQL.SELECT("ItemId, ItemDate, Description, Hours").
                                       FROM("{{timesheet}}").
                                       WHERE("PortalId", route.PortalId ).
                                       AND("UserId", route.UserId).
                                       AND("ItemDate", ">", DateTime.Today.AddDays(-28)).
                                       ORDERBY("ItemDate DESC").
                           ExecuteCollection<TimesheetItem>() 
                           ?? new List<TimesheetItem>();
            
            return vm;
        }

        public static TimesheetViewModel AddEntry(RouteInfo route, DateTime itemDate, string desc, double hours)
        {
            route.App.DB.SQL.INSERTINTO("{{timesheet}}", "PortalId, UserId, ItemDate, Description, Hours").
                           VALUES(route.PortalId, route.UserId, itemDate, desc, hours).
                           ExecuteNonquery();
            return Create(route);
        }

        public static TimesheetViewModel Delete(int itemId, RouteInfo route)
        {
            // Delete the item
            route.App.DB.SQL.DELETEFROM("{{timesheet}}").WHERE("ItemId", itemId).ExecuteNonquery();
            // Retun a new view model
            return Create(route);
        }

        public static TimesheetViewModel Update(int itemId, DateTime itemDate, string desc, double hours, RouteInfo route)
        {
            // Update the time entry
            route.App.DB.SQL.UPDATE("{{timesheet}}").SET("ItemDate", itemDate).SET("Description", desc).SET("Hours", hours).
                       WHERE("ItemId", itemId).ExecuteNonquery();

            // Return a new view model
            return Create(route);
        }



    }
}